package server

import (
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/consumers/publisher"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
)

// 验证rHash，返回true或false
func takeOffCodeOk(mobile string, mobileHash string) bool {
	sMobile, err := cache.GetRegisterVerify(mobileHash)
	if err != nil {
		return false
	}
	if sMobile != mobile {
		return false
	}
	return true
}

type LoginParam struct {
	SourceKey  string
	SourceId   int32
	Website    string
	Platform   uint32
	Ip         string
	DeviceInfo string
}

func (s *Server) GenLoginResp(user *models_main.User, param LoginParam) (*pb.LoginResp, error) {
	var mobileHash string
	user.LastIp = param.Ip
	user.BannedNum = 0 //登陆成功后，此项清0
	user.OnlineStatus = _const.ACCOUNT_ONLINE_STATUS_ONLINE
	if param.SourceId != 0 && len(param.SourceKey) < 3 { //如果传的是整型
		param.SourceKey = fmt.Sprint(param.SourceId)
	}
	if param.Platform == _const.LOGIN_PLATFORM_WEB || param.Platform == _const.LOGIN_PLATFORM_H5 { //pc、h5
		user.LoginSourceId = cache.GetSourceIdByUrl(param.Website)
	} else {
		user.LoginSourceId = param.SourceKey
	}

	token, err := s.UpdateUserLoginInfo(user, int(param.Platform)) //todo 异步，推nats队列
	if err != nil {
		return nil, err
	}

	err = cache.SetUserToken(user.Id, token, int(param.Platform))
	if err != nil {
		return nil, err
	}

	loginReq := &api_models.LoginReq{
		Ip:            param.Ip,
		LoginPlatform: int(param.Platform),
	}
	err = GenUserLog(user, loginReq, param.DeviceInfo)
	if err != nil {
		return nil, err
	}

	if user.RegSourceId != "" {
		err = global2.PublishChannelStats.Send(publisher.LoginChannelStats, user)
		if err != nil {
			global2.Log.Errorf("Nats publish chanel %s", err.Error())
		}
	}

	return &pb.LoginResp{
		Id: int32(user.Id),
		//Token:       user.Token,
		//TokenWeb:    user.TokenWeb,
		Token:       token,
		TokenWeb:    token,
		NickName:    user.NickName,
		Account:     user.Account,
		Avatar:      user.Avatar,
		AttentCount: uint32(cache.GetFansCount(user.Id)),
		Diamond:     uint32(user.Diamond),
		MobileHash:  mobileHash,
		Gold:        uint32(user.Gold),
	}, nil
}
